﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Models;
using ConcreteService;
using Infrastructures;
using System.IO;
using System.Net.Http.Headers;

namespace SponsorshipWeb.Controllers
{
    public class LoginController : ApiController
    {
        UserValidationService service = ServiceFactory.CreateInstance<UserValidationService>();
        UserInfoService userService = ServiceFactory.CreateInstance<UserInfoService>();

        #region 注册
        /// <summary>
        /// 用户注册-第一步
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public IHttpActionResult Post([FromBody]UserInfo value)
        {
            var validation = service.Get<UserValidation>(value.UserName);

            string resp = "";
            if (validation == null || string.IsNullOrWhiteSpace(validation.ValidNo)
                || value.NickName != validation.ValidNo || (DateTime.Now - validation.CreatedTime).Minutes > 15)
                resp = "验证码错误";

            else
            {
                value.Role = value.Role;
                value.NickName = string.Empty;
                value.Phone = value.UserName;
                value.CreateTime = DateTime.Now;
                UserInfoService userService = ServiceFactory.CreateInstance<UserInfoService>();
                service.Create(value, value.UserName);

                AuthUtil.Authorize(value);
                CacheManager.Delete<UserValidation>(value.UserName);
                value.Status = CommonStatus.SecondStep;
                service.Update(value, value.UserNo.ToString());
                resp = "2";
            }
            return Ok(new StringResponse()
            {
                Status = ResponseStatus.OK(),
                ResponseStr = resp
            });
        }

        /// <summary>
        /// 获取注册到第几步了
        /// </summary>
        /// <returns></returns>
        public IHttpActionResult GetStatus()
        {
            string status = "";
            var user = AuthUtil.GetAuthentication();
            if (user == null)
                status = "1";
            else
            {
                UserInfo userInfo = service.Get<UserInfo>(user.UserID.ToString());
                switch (userInfo.Status)
                {
                    case CommonStatus.SecondStep:
                        status = "2";
                        break;
                    case CommonStatus.ThirdStep:
                        status = "3";
                        break;
                    case CommonStatus.FourStep:
                        status = "4";
                        break;
                    case CommonStatus.FiveStep:
                        status = "5";
                        break;
                }
            }

            return Ok(new StringResponse()
            {
                Status = ResponseStatus.OK(),
                ResponseStr = status
            });
        }

        #endregion

        #region 图片验证码

        public HttpResponseMessage GetValidateCode()
        {
            System.Web.HttpContext context = System.Web.HttpContext.Current;
            Infrastructures.DataUtil.ValidateCode vCode = new Infrastructures.DataUtil.ValidateCode();
            string code = vCode.CreateValidateCode(5);
            context.Session["ValidateCode"] = code;
            var imgByte = vCode.CreateValidateGraphic(code);
            //从图片中读取流  

            var resp = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new ByteArrayContent(imgByte)

            };
            resp.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpg");
            return resp;
        }

        #endregion

        #region 获取手机验证码
        /// <summary>
        /// 获取验证码
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public string GetMessage(string id, string vcode)
        {
            var valcode = System.Web.HttpContext.Current.Session["ValidateCode"].ToString();
            if (valcode != vcode)
            {
                return ("验证码错误");
            }
            UserInfoService userService = ServiceFactory.CreateInstance<UserInfoService>();
            if (userService.IsUserExist(id))
                return null;

            UserValidation val = new UserValidation();
            val.AccountValue = id;
            val.AccountType = AccountType.Phone;
            val.ValidType = ValiationType.Register;
            val.CreatedTime = DateTime.Now;

            service.SendValidationMessage(val);

            return "value";
        }

        /// <summary>
        /// 忘记密码
        /// </summary>
        /// <param name="id"></param>
        /// <param name="vcode"></param>
        /// <returns></returns>
        [HttpGet]
        public string ValidatForgetPwd(string id, string vcode)
        {
            var valcode = System.Web.HttpContext.Current.Session["ValidateCode"].ToString();
            if (valcode != vcode)
            {
                return ("验证码错误");
            }
            string value = string.Empty;
            var info = userService.IsUserExist(id);
            if (info)
            {
                value = "value";
                UserValidation val = new UserValidation();
                val.AccountValue = id;
                val.AccountType = AccountType.Phone;
                val.ValidType = ValiationType.ChangePassword;
                val.CreatedTime = DateTime.Now;

                service.SendValidationMessage(val);
            }

            return value;
        }

        #endregion

        // GET api/login
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }




        [HttpGet]
        public string Get([FromUri]string id, [FromUri]string validType)
        {
            ValiationType type = (ValiationType)Enum.Parse(typeof(ValiationType), validType);

            UserInfoService userService = ServiceFactory.CreateInstance<UserInfoService>();
            bool isExist = true; //userService.IsUserExist(id);

            if (isExist && type == ValiationType.Register)
                return null;

            if (!isExist && type != ValiationType.Register)
                return null;

            UserValidation val = new UserValidation();
            val.AccountValue = id;
            val.AccountType = AccountType.Phone;
            val.ValidType = type;
            val.CreatedTime = DateTime.Now;

            service.SendValidationMessage(val);

            return "value";
        }

        [HttpGet]
        public IHttpActionResult ValidatePhone([FromUri]string id, [FromUri]ValiationType validType)
        {
            var user = AuthUtil.GetAuthentication();
            if (user == null)
                return BadRequest("请登录");
            string userid = user.UserID.ToString();
            string value = "";
            var info = userService.Get<UserInfo>(userid);
            if (info == null || info.UserName != id)
            {
                value = string.Empty;
            }
            else
            {
                value = "value";
                UserValidation val = new UserValidation();
                val.AccountValue = id;
                val.AccountType = AccountType.Phone;
                val.ValidType = validType;
                val.CreatedTime = DateTime.Now;

                service.SendValidationMessage(val);
            }
            return Ok(new StringResponse()
            {
                Status = ResponseStatus.OK(),
                ResponseStr = value
            });
        }

       

        [HttpGet]
        public string Get([FromUri]string id, [FromUri]string validType, [FromUri]string code)
        {
            ValiationType type = (ValiationType)Enum.Parse(typeof(ValiationType), validType);

            var validation = service.Get<UserValidation>(id);
            if (validation == null || string.IsNullOrWhiteSpace(validation.ValidNo)
                || code != validation.ValidNo || (DateTime.Now - validation.CreatedTime).Minutes > 15 || validation.ValidType != type)
                return null;

            return id;
        }

        // POST api/login


        // PUT api/login/5
        public string Put(string id, [FromBody]UserInfo value)
        {
            UserInfoService userService = ServiceFactory.CreateInstance<UserInfoService>();
            UserInfo user = null; //userService.GetUser(id);
            if (user == null)
                return null;

            //userService.UpdatePassword(user.UserNO, value.Password, user.UserNO.ToString());
            CacheManager.Delete<UserValidation>(id);
            return "success";
        }

        // DELETE api/login/5
        public void Delete(int id)
        {
        }
    }
}
